package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdminLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author rong
 */
@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    private final AdUserMapper adUserMapper;

    /**
     * 平台管理登录
     *
     * @param dtos
     * @return
     */
    @Override
    public ResponseResult adminLogin(AdminLoginDto dtos) {
        //判断数据是否为空
        if (StringUtils.isEmpty(dtos.getName()) || StringUtils.isEmpty(dtos.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<AdUser>()
                .eq(AdUser::getName, dtos.getName());
        List<AdUser> adUsers = adUserMapper.selectList(wrapper);
        if (adUsers.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        for (AdUser adUser : adUsers) {
            if (StringUtils.isEmpty(adUser.getSalt())) {
                adUser.setSalt("");
            }
            if (MD5Utils.encode(dtos.getName() + adUser.getSalt()).equals(adUser.getPassword())) {
                Map<String, Object> map = new HashMap<>();
                map.put("user", adUser);
                map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                return ResponseResult.okResult(map);
            }
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
    }
}
